package share.service;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import share.dao.entity.ShareDO;
import share.dao.mapper.ShareDOMapper;
import share.service.model.PageModel;
import share.service.model.ShareModel;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ShareServiceImpl implements ShareService {

    @Autowired
    private ShareDOMapper shareDOMapper;

    @Override
    public ShareModel addShare(ShareModel shareModel) {
        ShareDO shareDO = convertShareDOFromShareModel(shareModel);
        shareDOMapper.insertSelective(shareDO);
        shareModel.setId(shareDO.getId());
        return shareModel;
    }

    @Override
    public PageModel<ShareModel> findByPage(Integer begin, Integer pageSize) {
        PageModel<ShareModel> pageModel = new PageModel<>();
        pageModel.setCurrPage(begin);
        pageModel.setPageSize(pageSize);
        int totalCount = shareDOMapper.findCount();
        pageModel.setTotalCount(totalCount);

        double tx = (double) totalCount / pageSize;
        Double totalPage = Math.ceil(tx);
        pageModel.setTotalPage(totalPage.intValue());

        int beginStep = (begin -1) * pageSize;
        List<ShareDO> shareDOList = shareDOMapper.listShareByPage(beginStep, pageSize);

        List<ShareModel> shareModelList = shareDOList.stream().map(shareDO -> {
            ShareModel shareModel = new ShareModel();
            BeanUtils.copyProperties(shareDO, shareModel);
            return shareModel;
        }).collect(Collectors.toList());

        pageModel.setList(shareModelList);
        return pageModel;
    }

    @Override
    public int deleteShare(Integer id) {
        return shareDOMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int editShare(ShareModel share) {
        ShareDO shareDO = new ShareDO();
        BeanUtils.copyProperties(share, shareDO);
        return shareDOMapper.updateByPrimaryKeySelective(shareDO);
    }

    @Override
    public ShareModel getShareById(Integer id) {
        ShareDO shareDO = shareDOMapper.selectByPrimaryKey(id);
        ShareModel shareModel = new ShareModel();
        BeanUtils.copyProperties(shareDO, shareModel);
        return shareModel;
    }

    private ShareDO convertShareDOFromShareModel(ShareModel shareModel) {
        if (shareModel == null) {
            return null;
        }

        ShareDO shareDO = new ShareDO();
        shareDO.setShareCode(shareModel.getShareCode());
        shareDO.setShareName(shareModel.getShareName());
        shareDO.setCreateDate(shareModel.getCreateDate());
        return shareDO;
    }
}
